import { Button, Form, Input, Message } from '@arco-design/web-react';
import { useCallback } from 'react';
import { useNavigate } from 'react-router';
import { doRegister } from '../../../api/personal';

import './index.css';

const FormItem = Form.Item;

export interface RegisterForm {
  username: string,
  password: string,
}

export const RegisterComponent = () => {

  const [form] = Form.useForm<RegisterForm>();
  const navigate = useNavigate();

  const handleSubmit = useCallback(async (values: RegisterForm) => {
    const result = await doRegister(values);


    if (result.data.code === 200) {
      Message.loading({
        id: 'need_update',
        content: '注册成功，将在两秒后跳转到登陆页',
        duration: 2000
      });
      setTimeout(() => {
        navigate('/user/login');
      }, 2000);
    } else {
      Message.error(result.data.msg);
    }
  }, []);

  return <div className='register-component-wrapper'>
    <h1 className='register-component-title'>用户注册</h1>
    <Form<RegisterForm> onSubmit={handleSubmit} form={form} style={{ width: 600 }}>
      <FormItem<RegisterForm> rules={[{ required: true, message: '请输入用户名' }]} required field="username" label='用户名'>
        <Input placeholder='请输入用户名' />
      </FormItem>
      <FormItem<RegisterForm> style={{ marginTop: '20px' }} rules={[{ required: true, message: '请输入密码' }]} required field="password" label='密码'>
        <Input placeholder='请输入密码' />
      </FormItem>
      <FormItem
        style={{ marginTop: '50px' }}
        wrapperCol={{
          offset: 5,
        }}
      >
        <Button onClick={() => { form.submit() }} type='primary' style={{ width: '475px' }}>注册</Button>
      </FormItem>
    </Form>
  </div>
}
